package com.example.ilvuuz.controller;

import com.example.ilvuuz.common.Result;
import com.example.ilvuuz.dto.LoginDTO;
import com.example.ilvuuz.entity.User;
import com.example.ilvuuz.service.UserService;
import com.example.ilvuuz.utils.JwtUtil;
import com.example.ilvuuz.utils.ThreadLocalUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


@Api(tags="用户接口")
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    
    @Autowired
    private JwtUtil jwtUtil;

    @ApiOperation("注册接口")
    @PostMapping("/register")
    public Result<Void> register(@RequestBody User user) {
        try {
            userService.register(user);
            return Result.success();
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    @ApiOperation("用户登录")
    @PostMapping("/login")
    public Result<String> login(@RequestBody LoginDTO loginDTO, HttpServletResponse response) {
        try {
            String token = userService.login(loginDTO.getUsername(), loginDTO.getPassword());
            
            // 设置cookie
            Cookie cookie = new Cookie("token", token);
            cookie.setPath("/");
            cookie.setMaxAge(60); // 7天有效期
            cookie.setHttpOnly(true); // 防止XSS攻击
            response.addCookie(cookie);
            
            return Result.success("登录成功", token);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    @ApiOperation("获取用户信息")
    @GetMapping("/info")
    public Result<User> getUserInfo() {
        try {
            // 从ThreadLocal中获取当前登录用户的用户名
            String username = (String) ThreadLocalUtil.get();
            User user = userService.getByUsername(username);
            return Result.success(user);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    @ApiOperation("检查token有效性")
    @GetMapping("/check-token")
    public Result<User> checkToken(@RequestHeader("Authorization") String token) {
        try {
            // 验证token
            if (token == null || token.isEmpty()) {
                return Result.error("未登录");
            }
            
            // 从token中获取用户信息
            String username = (String) ThreadLocalUtil.get();
            User user = userService.getByUsername(username);
            if (user == null) {
                return Result.error("用户不存在");
            }
            
            return Result.success(user);
        } catch (Exception e) {
            return Result.error("token无效");
        }
    }
} 